package com.study.storage.cotroller;

import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author
 */
@Slf4j
@RestController
public class StorageController {

	private static final String SUCCESS = "SUCCESS";
	private static final String FAIL = "FAIL";
	private final JdbcTemplate jdbcTemplate;

	public StorageController(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@RequestMapping(value = "/storage/{commodityCode}/{count}", method = RequestMethod.GET, produces = "application/json")
	public String echo(@PathVariable String commodityCode, @PathVariable int count) {
		log.info("Storage Service Begin ... xid: " + RootContext.getXID());
		String sql = "update storage_tbl set count = count - ? where commodity_code = ?";
		int result = jdbcTemplate.update(sql, new Object[] { count, commodityCode });
		log.info("Storage Service End ...result:{},sql={}",result,sql);
		return (result == 1) ? SUCCESS : FAIL;
	}
}